<template>
  <div class="resource-detail-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="breadcrumb">
          <router-link to="/resources" class="breadcrumb-link">学习资源</router-link>
          <span class="breadcrumb-separator">/</span>
          <span class="breadcrumb-current">{{ resource.title || '资源详情' }}</span>
        </div>
        <h1 class="page-title">{{ resource.title || '资源详情' }}</h1>
        <p class="page-subtitle">{{ resource.description || '暂无描述' }}</p>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 资源详情内容 -->
    <div v-else-if="resource.id" class="resource-content">
      <div class="content-layout">
        <!-- 左侧主要内容 -->
        <div class="main-content">
          <!-- 资源预览 -->
          <div class="resource-preview-card">
            <div class="resource-cover" v-if="resource.coverImage">
              <img :src="resource.coverImage" :alt="resource.title" />
            </div>
            
            <div class="resource-basic-info">
              <div class="resource-header">
                <h2 class="resource-title">{{ resource.title }}</h2>
                <el-tag :type="getResourceTypeTag()" size="large">{{ getResourceTypeText() }}</el-tag>
              </div>
              
              <p class="resource-description">{{ resource.description }}</p>
              
              <div class="resource-meta">
                <div class="meta-item">
                  <el-icon><User /></el-icon>
                  <span>作者：{{ resource.author?.username || '未知' }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Calendar /></el-icon>
                  <span>发布时间：{{ formatDate(resource.createdAt) }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Download /></el-icon>
                  <span>下载次数：{{ resource.downloadCount || 0 }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><View /></el-icon>
                  <span>浏览次数：{{ resource.viewCount || 0 }}</span>
                </div>
              </div>
              
              <div class="resource-tags" v-if="resource.tags && resource.tags.length">
                <el-tag v-for="tag in resource.tags" :key="tag.id" size="small" class="tag">
                  {{ tag.name }}
                </el-tag>
              </div>
            </div>
          </div>

          <!-- 资源操作 -->
          <div class="resource-actions-card">
            <h3 class="card-title">资源操作</h3>
            <div class="action-buttons">
              <el-button 
                type="primary" 
                :loading="isDownloading"
                @click="handleDownload"
                class="action-btn"
              >
                <el-icon><Download /></el-icon>
                下载资源
              </el-button>
              <el-button 
                :type="isFavorite ? 'danger' : 'default'"
                @click="handleFavorite"
                class="action-btn"
              >
                <el-icon><Star /></el-icon>
                {{ isFavorite ? '取消收藏' : '收藏资源' }}
              </el-button>
              <el-button type="default" @click="handleShare" class="action-btn">
                <el-icon><Share /></el-icon>
                分享资源
              </el-button>
            </div>
          </div>

          <!-- 资源详情 -->
          <div class="resource-details-card">
            <h3 class="card-title">资源详情</h3>
            <div class="details-content">
              <div class="detail-item">
                <span class="detail-label">文件大小：</span>
                <span class="detail-value">{{ resource.fileSize || '未知' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">文件格式：</span>
                <span class="detail-value">{{ resource.fileFormat || '未知' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">资源分类：</span>
                <span class="detail-value">{{ resource.category?.name || '未分类' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">更新时间：</span>
                <span class="detail-value">{{ formatDate(resource.updatedAt) }}</span>
              </div>
            </div>
          </div>

          <!-- 用户评论 -->
          <div class="resource-comments-card">
            <h3 class="card-title">用户评论 ({{ comments.length }})</h3>
            <div class="comment-form">
              <el-input
                v-model="newComment"
                type="textarea"
                :rows="3"
                placeholder="写下你的评论..."
                class="comment-input"
              />
              <div class="comment-actions">
                <el-button type="primary" @click="handleSubmitComment" :loading="isSubmitting">
                  发表评论
                </el-button>
              </div>
            </div>
            
            <div class="comments-list">
              <div v-for="comment in comments" :key="comment.id" class="comment-item">
                <div class="comment-avatar">
                  <img :src="comment.user?.avatar || '/default-avatar.png'" :alt="comment.user?.username" />
                </div>
                <div class="comment-content">
                  <div class="comment-header">
                    <span class="comment-user">{{ comment.user?.username }}</span>
                    <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
                  </div>
                  <p class="comment-text">{{ comment.content }}</p>
                  <div class="comment-actions">
                    <el-button type="text" size="small" @click="handleLikeComment(comment.id)">
                      <el-icon><Star /></el-icon>
                      {{ comment.likeCount || 0 }}
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar">
          <!-- 相关资源 -->
          <div class="related-resources-card">
            <h3 class="card-title">相关资源</h3>
            <div class="related-list">
              <div v-for="related in relatedResources" :key="related.id" class="related-item" @click="navigateToResource(related.id)">
                <div class="related-cover">
                  <img :src="related.coverImage" :alt="related.title" />
                </div>
                <div class="related-info">
                  <h4 class="related-title">{{ related.title }}</h4>
                  <div class="related-meta">
                    <span class="related-downloads">{{ related.downloadCount }} 下载</span>
                    <span class="related-rating">{{ related.rating }} 分</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 作者信息 -->
          <div class="author-info-card">
            <h3 class="card-title">作者信息</h3>
            <div class="author-info">
              <div class="author-avatar">
                <img :src="resource.author?.avatar || '/default-avatar.png'" :alt="resource.author?.username" />
              </div>
              <div class="author-details">
                <h4 class="author-name">{{ resource.author?.username }}</h4>
                <p class="author-bio">{{ resource.author?.bio || '暂无简介' }}</p>
                <div class="author-stats">
                  <span class="stat">资源 {{ resource.author?.resourceCount || 0 }}</span>
                  <span class="stat">粉丝 {{ resource.author?.followerCount || 0 }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 404状态 -->
    <div v-else class="not-found">
      <el-empty description="资源不存在或已被删除">
        <el-button type="primary" @click="$router.push('/resources')">
          返回资源列表
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Calendar, Download, View, Star, Share } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/common'
import { addBrowseHistory } from '@/api/history'
import { addCollection, removeCollection } from '@/api/collection'

// 路由
const route = useRoute()
const router = useRouter()

// 数据状态
const loading = ref(false)
const resource = ref<any>({})
const comments = ref<any[]>([])
const relatedResources = ref<any[]>([])
const newComment = ref('')
const isDownloading = ref(false)
const isSubmitting = ref(false)
const isFavorite = ref(false)

// 计算属性
const resourceId = computed(() => route.params.id as string)

// 获取资源类型标签
const getResourceTypeTag = () => {
  const typeMap: Record<string, string> = {
    'pdf': 'danger',
    'video': 'success',
    'audio': 'warning',
    'image': 'info',
    'document': 'primary'
  }
  return typeMap[resource.value.type] || 'info'
}

// 获取资源类型文本
const getResourceTypeText = () => {
  const typeMap: Record<string, string> = {
    'pdf': 'PDF文档',
    'video': '视频文件',
    'audio': '音频文件',
    'image': '图片文件',
    'document': '文档文件'
  }
  return typeMap[resource.value.type] || '未知类型'
}

// 加载资源详情
const loadResourceDetail = async () => {
  try {
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟数据
    resource.value = {
      id: resourceId.value,
      title: '2024年公务员考试行测必做1000题',
      description: '精选历年行测真题和高质量模拟题，包含详细解析和解题技巧，帮助考生全面提升行测能力。',
      type: 'pdf',
      fileSize: '15.2MB',
      fileFormat: 'PDF',
      coverImage: 'https://picsum.photos/id/24/800/400',
      downloadCount: 1254,
      viewCount: 3689,
      favoriteCount: 567,
      author: {
        id: 3,
        username: '资料大全',
        avatar: 'https://picsum.photos/id/1025/200/200',
        bio: '专注于公务员考试资料整理，已发布100+优质资源',
        resourceCount: 45,
        followerCount: 1234
      },
      category: { id: 3, name: '行测资料' },
      tags: [
        { id: 1, name: '行测' },
        { id: 2, name: '真题' },
        { id: 3, name: '必做' }
      ],
      createdAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
      updatedAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString()
    }
    
    // 记录浏览历史
    const userId = localStorage.getItem('userId') || localStorage.getItem('user_id') || '1'
    if (userId && resource.value) {
      // 创建浏览历史数据
      const historyData = {
        id: Date.now(),
        userId: Number(userId),
        contentType: 'RESOURCE',
        contentId: Number(resourceId.value),
        contentTitle: resource.value.title,
        contentDescription: resource.value.description?.substring(0, 100),
        contentUrl: `/resources/detail/${resourceId.value}`,
        browseTime: new Date().toISOString(),
        createdAt: new Date().toISOString()
      };
      
      try {
        // 尝试调用API
        // 使用静态导入的addBrowseHistory
        await addBrowseHistory({
          userId: Number(userId),
          contentType: 'RESOURCE',
          contentId: Number(resourceId.value),
          contentTitle: resource.value.title,
          contentDescription: resource.value.description?.substring(0, 100),
          contentUrl: `/resources/detail/${resourceId.value}`
        })
        console.log('API资源浏览历史记录成功')
      } catch (historyError) {
        console.error('API记录资源浏览历史失败，使用本地存储:', historyError)
      }
      
      // 无论API是否成功，都保存到本地存储
      const historyKey = `browse_history_${userId}`;
      const existingHistory = JSON.parse(localStorage.getItem(historyKey) || '[]');
      
      // 检查是否已存在相同的浏览记录
      const existingIndex = existingHistory.findIndex((item: any) => 
        item.contentType === 'RESOURCE' && item.contentId === Number(resourceId.value)
      );
      
      if (existingIndex !== -1) {
        // 如果已存在，更新浏览时间
        existingHistory[existingIndex].browseTime = new Date().toISOString();
      } else {
        // 如果不存在，添加新记录
        existingHistory.unshift(historyData);
      }
      
      // 只保留最近100条记录
      if (existingHistory.length > 100) {
        existingHistory.splice(100);
      }
      
      localStorage.setItem(historyKey, JSON.stringify(existingHistory));
      console.log('资源浏览历史已保存到本地存储');
    }
    
    comments.value = [
      {
        id: 1,
        content: '资料很全面，解析也很详细，对备考很有帮助！',
        user: { username: '备考小白', avatar: 'https://picsum.photos/id/1011/200/200' },
        likeCount: 5,
        createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
      },
      {
        id: 2,
        content: '题目质量很高，推荐下载！',
        user: { username: '努力备考中', avatar: 'https://picsum.photos/id/1012/200/200' },
        likeCount: 3,
        createdAt: new Date(Date.now() - 5 * 60 * 60 * 1000).toISOString()
      }
    ]
    
    relatedResources.value = [
      {
        id: 2,
        title: '申论范文100篇',
        coverImage: 'https://picsum.photos/id/25/300/200',
        downloadCount: 2103,
        rating: 4.8
      },
      {
        id: 3,
        title: '面试技巧大全',
        coverImage: 'https://picsum.photos/id/26/300/200',
        downloadCount: 1890,
        rating: 4.6
      }
    ]
    
  } catch (error) {
    console.error('加载资源详情失败:', error)
    ElMessage.error('加载资源详情失败')
  } finally {
    loading.value = false
  }
}

// 下载资源
const handleDownload = async () => {
  try {
    isDownloading.value = true
    await new Promise(resolve => setTimeout(resolve, 2000))
    resource.value.downloadCount = (resource.value.downloadCount || 0) + 1
    ElMessage.success('资源下载完成')
  } catch (error) {
    ElMessage.error('下载失败')
  } finally {
    isDownloading.value = false
  }
}

// 收藏/取消收藏
const handleFavorite = async () => {
  if (!resource.value) return
  
  try {
    const userId = localStorage.getItem('userId') || localStorage.getItem('user_id') || '1'
    
    if (isFavorite.value) {
      // 取消收藏
      try {
        // 使用静态导入的removeCollection
        await removeCollection(Number(userId), 'RESOURCE', Number(resource.value.id))
        isFavorite.value = false
        resource.value.favoriteCount = Math.max(0, (resource.value.favoriteCount || 0) - 1)
        ElMessage.success('取消收藏成功')
      } catch (error) {
        console.error('取消收藏失败:', error)
        ElMessage.error('取消收藏失败')
      }
    } else {
      // 添加收藏
      try {
        // 使用静态导入的addCollection
        await addCollection({
          userId: Number(userId),
          contentType: 'RESOURCE',
          contentId: Number(resource.value.id),
          contentTitle: resource.value.title,
          contentDescription: resource.value.description?.substring(0, 100),
          contentUrl: `/resources/detail/${resource.value.id}`
        })
        isFavorite.value = true
        resource.value.favoriteCount = (resource.value.favoriteCount || 0) + 1
        ElMessage.success('收藏成功')
      } catch (error) {
        console.error('收藏失败:', error)
        ElMessage.error('收藏失败')
      }
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 分享资源
const handleShare = () => {
  const url = window.location.href
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 提交评论
const handleSubmitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  try {
    isSubmitting.value = true
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const comment = {
      id: Date.now(),
      content: newComment.value,
      user: { username: '当前用户', avatar: '/default-avatar.png' },
      likeCount: 0,
      createdAt: new Date().toISOString()
    }
    
    comments.value.unshift(comment)
    newComment.value = ''
    ElMessage.success('评论发表成功')
  } catch (error) {
    ElMessage.error('发表评论失败')
  } finally {
    isSubmitting.value = false
  }
}

// 点赞评论
const handleLikeComment = (commentId: number) => {
  const comment = comments.value.find(c => c.id === commentId)
  if (comment) {
    comment.likeCount = (comment.likeCount || 0) + 1
    ElMessage.success('点赞成功')
  }
}

// 跳转到相关资源
const navigateToResource = (id: number) => {
  router.push(`/resource/${id}`)
}

// 组件挂载时加载数据
onMounted(() => {
  loadResourceDetail()
})
</script>

<style lang="scss" scoped>
.resource-detail-view {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
  
  .header-content {
    .breadcrumb {
      margin-bottom: 10px;
      font-size: 14px;
      color: #666;
      
      .breadcrumb-link {
        color: #409eff;
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
      
      .breadcrumb-separator {
        margin: 0 8px;
        color: #ccc;
      }
      
      .breadcrumb-current {
        color: #333;
      }
    }
    
    .page-title {
      font-size: 28px;
      font-weight: 600;
      color: #333;
      margin: 0 0 10px 0;
    }
    
    .page-subtitle {
      font-size: 16px;
      color: #666;
      margin: 0;
    }
  }
}

.loading-container {
  padding: 40px;
}

.resource-content {
  .content-layout {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 30px;
    
    @media (max-width: 768px) {
      grid-template-columns: 1fr;
      gap: 20px;
    }
  }
  
  .main-content {
    .resource-preview-card {
      background: white;
      border-radius: 12px;
      padding: 30px;
      margin-bottom: 30px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      
      .resource-cover {
        width: 100%;
        height: 300px;
        border-radius: 8px;
        overflow: hidden;
        margin-bottom: 20px;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .resource-basic-info {
        .resource-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 15px;
          
          .resource-title {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin: 0;
          }
        }
        
        .resource-description {
          font-size: 16px;
          color: #666;
          line-height: 1.6;
          margin: 0 0 20px 0;
        }
        
        .resource-meta {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
          gap: 15px;
          margin-bottom: 20px;
          
          .meta-item {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #666;
            font-size: 14px;
            
            .el-icon {
              font-size: 16px;
            }
          }
        }
        
        .resource-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          
          .tag {
            margin: 0;
          }
        }
      }
    }
    
    .resource-actions-card,
    .resource-details-card,
    .resource-comments-card {
      background: white;
      border-radius: 12px;
      padding: 30px;
      margin-bottom: 30px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      
      .card-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin: 0 0 20px 0;
      }
    }
    
    .action-buttons {
      display: flex;
      gap: 15px;
      flex-wrap: wrap;
      
      .action-btn {
        flex: 1;
        min-width: 120px;
      }
    }
    
    .details-content {
      .detail-item {
        display: flex;
        padding: 10px 0;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .detail-label {
          font-weight: 500;
          color: #333;
          width: 100px;
          flex-shrink: 0;
        }
        
        .detail-value {
          color: #666;
        }
      }
    }
    
    .comment-form {
      margin-bottom: 30px;
      
      .comment-input {
        margin-bottom: 15px;
      }
      
      .comment-actions {
        display: flex;
        justify-content: flex-end;
      }
    }
    
    .comments-list {
      .comment-item {
        display: flex;
        gap: 15px;
        padding: 20px 0;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .comment-avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          overflow: hidden;
          flex-shrink: 0;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
        
        .comment-content {
          flex: 1;
          
          .comment-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 8px;
            
            .comment-user {
              font-weight: 500;
              color: #333;
            }
            
            .comment-time {
              font-size: 12px;
              color: #999;
            }
          }
          
          .comment-text {
            color: #666;
            line-height: 1.5;
            margin: 0 0 10px 0;
          }
          
          .comment-actions {
            .el-button {
              padding: 4px 8px;
              font-size: 12px;
            }
          }
        }
      }
    }
  }
  
  .sidebar {
    .related-resources-card,
    .author-info-card {
      background: white;
      border-radius: 12px;
      padding: 20px;
      margin-bottom: 20px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      
      .card-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin: 0 0 15px 0;
      }
    }
    
    .related-list {
      .related-item {
        display: flex;
        gap: 10px;
        padding: 10px 0;
        border-bottom: 1px solid #f0f0f0;
        cursor: pointer;
        transition: background-color 0.2s;
        
        &:hover {
          background-color: #f8f9fa;
        }
        
        &:last-child {
          border-bottom: none;
        }
        
        .related-cover {
          width: 60px;
          height: 40px;
          border-radius: 4px;
          overflow: hidden;
          flex-shrink: 0;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
        
        .related-info {
          flex: 1;
          
          .related-title {
            font-size: 14px;
            font-weight: 500;
            color: #333;
            margin: 0 0 5px 0;
            line-height: 1.3;
          }
          
          .related-meta {
            display: flex;
            gap: 10px;
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
    
    .author-info {
      .author-avatar {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        overflow: hidden;
        margin: 0 auto 15px;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .author-details {
        text-align: center;
        
        .author-name {
          font-size: 16px;
          font-weight: 600;
          color: #333;
          margin: 0 0 8px 0;
        }
        
        .author-bio {
          font-size: 14px;
          color: #666;
          line-height: 1.4;
          margin: 0 0 15px 0;
        }
        
        .author-stats {
          display: flex;
          justify-content: center;
          gap: 15px;
          
          .stat {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }
}

.not-found {
  padding: 60px 20px;
  text-align: center;
}
</style>
